package com.poly.ureport.report;

import com.bstek.ureport.provider.report.ReportFile;
import com.bstek.ureport.provider.report.ReportProvider;
import com.poly.common.core.enums.CommonStatus;
import com.poly.common.core.text.CharsetKit;
import com.poly.ureport.domain.SysReport;
import com.poly.ureport.service.ISysReportService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class MysqlReportProvider implements ReportProvider {

    @Autowired
    private ISysReportService reportService;

    private static final String NAME = "MYSQL数据库存储（推荐）";

    // 特定前缀，ureport底层会调用 getPrefix 方法来获取报表操作的Provier类
    private String prefix = "mysql:";

    // 是否禁用
    private boolean disabled;

    @Override
    public InputStream loadReport(String file) {
        SysReport report = reportService.getByName(getCorrectName(file));
        byte[] content = report.getContent().getBytes(CharsetKit.CHARSET_UTF_8);
        ByteArrayInputStream inputStream = new ByteArrayInputStream(content);
        return inputStream;
    }

    @Override
    public void deleteReport(String file) {
        reportService.deleteByName(getCorrectName(file));
    }

    @Override
    public List<ReportFile> getReportFiles() {
        List<SysReport> list = reportService.list();
        List<ReportFile> reportList = new ArrayList<>();
        for (SysReport report : list) {
            reportList.add(new ReportFile(report.getName(), report.getUpdateTime()));
        }
        return reportList;
    }

    @Override
    public void saveReport(String file, String content) {
        String filename = getCorrectName(file);
        SysReport ureport = reportService.getByName(filename);
        if(ureport == null){
            ureport = new SysReport();
            ureport.setName(filename);
            ureport.setContent(content);
            ureport.setStatus(CommonStatus.normal.getValue());
            ureport.setRemark(file);
            ureport.setCreateTime(new Date());
            ureport.setUpdateTime(new Date());
            reportService.save(ureport);
        }else {
            ureport.setContent(content);
            ureport.setUpdateTime(new Date());
            reportService.updateById(ureport);
        }
    }

    @Override
    public String getName() {
        return NAME;
    }

    @Override
    public boolean disabled() {
        return disabled;
    }

    @Override
    public String getPrefix() {
        return prefix;
    }
    /**
     * 获取没有前缀的文件名
     * @param name
     * @return
     */
    private String getCorrectName(String name)
    {
        if(name.startsWith(prefix))
        {
            name = name.substring(prefix.length(), name.length());
        }
        return name;
    }
}
